import base64
import pickle

from django_redis import get_redis_connection


def merge_cart_cookie_to_redis(request, response, user):
    """
    合并购物车
    :param request: 用于获取cookie
    :param response: 用于清除cookie
    :param user: 用于标识哪个用户合并购物车
    :return: response
    购物车数据哈希
    key: cart_用户id
    value: {sku_id:count, sku_id: count}

    购物车勾选记录-Set类型
    key: cart_selected_用户id
    value: {sku_id, sku_id}
    {
        sku_id: {
            "count": xxx,  // 数量
            "selected": True  // 是否勾选
        },
        sku_id: {
            "count": xxx,
            "selected": False
        },
        ...
    }
    """
    # 从cookie中获取购物车数据
    cookie_cart = request.COOKIES.get('cart')
    if not cookie_cart:
        # 如果cookie中没有购物车信息，那么则直接登录不用合并
        return response
    # 解码并且转换未字典数据
    cart = pickle.loads(base64.b64decode(cookie_cart.encode()))
    # 构建redis连接对象
    redis_conn = get_redis_connection('cart')
    pl = redis_conn.pipeline()
    # 如果cookie中商品信息和redis中商品信息重复以cookie中为准
    for sku_id, sku_dict in cart.items():
        count = sku_dict.get('count')
        selected = sku_dict.get('selected')
        pl.hset('cart_%s' % user.id, sku_id, count)
        if selected:
            pl.sadd('cart_selected_%s' % user.id, sku_id)
        else:
            pl.srem('cart_selected_%s' % user.id, sku_id)
    pl.execute()

    # 清除cookie信息
    response.delete_cookie('cart')
    return response
